'''
Created on 18.05.2014
important link:
    - https://dev.mysql.com/doc/connector-python/en/connector-python-connectargs.html
@author: Wolfgang
'''
import mysql.connector
import logging

def connect():
    # Return connection to database
    logging.debug('Connect to Database 10.0.0.80');
    return mysql.connector.connect(user='wolfgang', password='wolfgang',database='racecontrol', host='10.0.0.80', port='3306' ) 

def finish(connection):
    logging.debug('close connection');
    connection.close()
def insertLap(tagId,raceId, connection):
    # query for starter by tagId and competitionId 
    add_lap = ("INSERT INTO lap"
               "(raceId,tagId)"
               "VALUES(%s, %s)")
    data_lap = (raceId, tagId)
    # Insert Data
    try:
        cursor = connection.cursor()
        cursor.execute(add_lap,data_lap)
        connection.commit();
        cursor.close();
    except:
        logging.error("Cannot Insert Lap");
        connection.rollback();
        cursor.close();
    # Do not close connection because this is done by calling method
def getActiveCompetition(connection):
    query = "SELECT raceid FROM race WHERE active = '1'"
    logging.debug('Execute Query: '+ query);
    cursor = connection.cursor()
    cursor.execute(query)
    result = cursor.fetchall()
    if len(result)> 1:
        cursor.close()
        raise NameError("no_Single_Result")
    cursor.close()
    return result[0][0] #return first row, first element which indicates the sid value
